<template>
  <div class="student-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <button class="back-btn" @click="goBack">
        ← 返回
      </button>
      <h1>👨‍🎓 学生管理</h1>
    </div>

    <!-- 标签页 -->
    <div class="tabs">
      <button
        :class="['tab-btn', { active: activeTab === 'class' }]"
        @click="activeTab = 'class'"
      >
        📚 分班管理
      </button>
      <button
        :class="['tab-btn', { active: activeTab === 'info' }]"
        @click="activeTab = 'info'"
      >
        👥 学生信息管理
      </button>
    </div>

    <!-- 分班管理 -->
    <div v-if="activeTab === 'class'" class="tab-content">
      <div class="section-header">
        <h2>分班管理</h2>
        <button class="btn-primary" @click="showAddClassDialog = true">
          + 创建班级
        </button>
      </div>

      <div class="class-list-container">
        <div v-if="loading" class="empty-state loading">
          <p>加载中...</p>
        </div>
        <template v-else>
          <template v-if="Object.keys(groupedClasses).length > 0">
            <div v-for="(classList, category) in groupedClasses" :key="category" class="class-category">
              <div class="category-header">
                <h3 class="category-title">{{ category }}</h3>
                <span class="category-count">({{ classList.length }}个班级)</span>
              </div>
              <div class="class-list">
                <div class="class-card" v-for="classItem in classList" :key="classItem.id">
                  <div class="class-header">
                    <h3>{{ classItem.name }}</h3>
                    <div class="class-info">
                      <span>年龄: {{ classItem.ageRange }}</span>
                      <span>学生数: {{ classItem.studentCount }}/{{ classItem.maxStudents }}</span>
                    </div>
                  </div>
                  <div class="class-actions">
                    <button class="btn-secondary" @click="viewClassStudents(classItem)">查看学生</button>
                    <button class="btn-secondary" @click="editClass(classItem)">编辑</button>
                    <button class="btn-danger" @click="deleteClass(classItem)">删除</button>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <div v-else class="empty-state">
            <p>暂无班级，请创建班级</p>
          </div>
        </template>
      </div>
    </div>

    <!-- 学生信息管理 -->
    <div v-if="activeTab === 'info'" class="tab-content">
      <div class="section-header">
        <h2>学生信息管理</h2>
        <div class="search-bar">
          <input
            v-model="searchKeyword"
            type="text"
            placeholder="搜索学生姓名、用户名..."
            class="search-input"
          />
          <select v-model="selectedClass" class="class-filter">
            <option value="">全部班级</option>
            <option v-for="classItem in classes" :key="classItem.id" :value="classItem.id">
              {{ classItem.name }}
            </option>
          </select>
        </div>
      </div>

      <div class="student-table">
        <div v-if="loadingStudents" class="empty-state loading">
          <p>加载中...</p>
        </div>
        <template v-else>
          <table>
            <thead>
              <tr>
                <th>用户名</th>
                <th>昵称</th>
                <th>班级</th>
                <th>年龄</th>
                <th>学习进度</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="student in filteredStudents" :key="student.id">
                <td>{{ student.username }}</td>
                <td>{{ student.nickname || '-' }}</td>
                <td>{{ student.className || '未分班' }}</td>
                <td>{{ student.age ? student.age + '岁' : '-' }}</td>
                <td>
                  <div class="progress-bar">
                    <div class="progress-fill" :style="{ width: student.progress + '%' }"></div>
                    <span class="progress-text">{{ student.progress }}%</span>
                  </div>
                </td>
                <td>
                  <button class="btn-link" @click="viewStudentDetail(student)">详情</button>
                  <button class="btn-link" @click="editStudent(student)">编辑</button>
                </td>
              </tr>
            </tbody>
          </table>
          <div v-if="!loadingStudents && filteredStudents.length === 0" class="empty-state">
            <p>暂无学生数据</p>
          </div>
        </template>
      </div>
    </div>

    <!-- 创建/编辑班级对话框 -->
    <div v-if="showAddClassDialog" class="modal-overlay" @click="closeClassDialog">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>{{ editingClass ? '编辑班级' : '创建班级' }}</h2>
          <button class="close-btn" @click="closeClassDialog">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveClass">
            <div class="form-group">
              <label>班级名称 <span class="required">*</span></label>
              <input
                v-model="classForm.name"
                type="text"
                placeholder="请输入班级名称"
                required
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>班级类别 <span class="required">*</span></label>
              <select v-model="classForm.classCategory" required class="form-input">
                <option value="">请选择班级类别</option>
                <option value="提高">提高</option>
                <option value="进阶">进阶</option>
                <option value="基础">基础</option>
                <option value="启蒙">启蒙</option>
              </select>
            </div>
            <div class="form-group">
              <label>年龄范围 <span class="required">*</span></label>
              <select v-model="classForm.ageRange" required class="form-input">
                <option value="">请选择年龄范围</option>
                <option value="3-4岁">3-4岁</option>
                <option value="5-6岁">5-6岁</option>
                <option value="7-8岁">7-8岁</option>
                <option value="9-10岁">9-10岁</option>
                <option value="11-12岁">11-12岁</option>
                <option value="13-14岁">13-14岁</option>
                <option value="15-16岁">15-16岁</option>
              </select>
            </div>
            <div class="form-group">
              <label>最大学生数 <span class="required">*</span></label>
              <input
                v-model.number="classForm.maxStudents"
                type="number"
                min="1"
                placeholder="请输入最大学生数"
                required
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>班级描述</label>
              <textarea
                v-model="classForm.description"
                placeholder="请输入班级描述（可选）"
                rows="3"
                class="form-input"
              ></textarea>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn-cancel" @click="closeClassDialog">取消</button>
              <button type="submit" class="btn-submit">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 学生详情对话框 -->
    <div v-if="showStudentDetailDialog" class="modal-overlay" @click="closeStudentDetailDialog">
      <div class="modal-content student-detail-modal" @click.stop>
        <div class="modal-header">
          <h2>学生详情</h2>
          <button class="close-btn" @click="closeStudentDetailDialog">×</button>
        </div>
        <div class="modal-body">
          <div v-if="loadingStudentDetail" class="loading-state">
            <p>加载中...</p>
          </div>
          <div v-else-if="studentDetail" class="student-detail-content">
            <!-- 学生基本信息 -->
            <div class="detail-section">
              <h3 class="section-title">基本信息</h3>
              <div class="detail-grid">
                <div class="detail-item">
                  <label>用户名：</label>
                  <span>{{ studentDetail.username || '-' }}</span>
                </div>
                <div class="detail-item">
                  <label>昵称：</label>
                  <span>{{ studentDetail.nickname || '-' }}</span>
                </div>
                <div class="detail-item">
                  <label>年龄：</label>
                  <span>{{ studentDetail.age ? studentDetail.age + '岁' : '-' }}</span>
                </div>
                <div class="detail-item">
                  <label>班级：</label>
                  <span>{{ studentDetail.className || '未分班' }}</span>
                </div>
                <div class="detail-item">
                  <label>学习进度：</label>
                  <span>{{ studentDetail.progress || 0 }}%</span>
                </div>
                <div class="detail-item">
                  <label>邮箱：</label>
                  <span>{{ studentDetail.email || '-' }}</span>
                </div>
                <div class="detail-item">
                  <label>电话：</label>
                  <span>{{ studentDetail.phone || '-' }}</span>
                </div>
                <div class="detail-item">
                  <label>状态：</label>
                  <span>{{ studentDetail.status === '0' ? '正常' : '停用' }}</span>
                </div>
              </div>
            </div>

            <!-- 家长信息 -->
            <div class="detail-section">
              <h3 class="section-title">家长信息</h3>
              <div v-if="studentDetail.parents && studentDetail.parents.length > 0" class="parents-list">
                <div v-for="(parent, index) in studentDetail.parents" :key="index" class="parent-card">
                  <div class="parent-info">
                    <div class="parent-item">
                      <label>关系：</label>
                      <span>{{ parent.relationType === 'parent' ? '家长' : parent.relationType || '家长' }}</span>
                    </div>
                    <div class="parent-item">
                      <label>用户名：</label>
                      <span>{{ parent.username || '-' }}</span>
                    </div>
                    <div class="parent-item">
                      <label>昵称：</label>
                      <span>{{ parent.nickname || '-' }}</span>
                    </div>
                    <div class="parent-item">
                      <label>邮箱：</label>
                      <span>{{ parent.email || '-' }}</span>
                    </div>
                    <div class="parent-item">
                      <label>电话：</label>
                      <span>{{ parent.phone || '-' }}</span>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="empty-state">
                <p>暂无家长信息</p>
              </div>
            </div>
          </div>
          <div v-else class="error-state">
            <p>加载失败，请重试</p>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn-submit" @click="closeStudentDetailDialog">关闭</button>
        </div>
      </div>
    </div>

    <!-- 编辑学生对话框 -->
    <div v-if="showEditStudentDialog" class="modal-overlay" @click="closeEditStudentDialog">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>编辑学生</h2>
          <button class="close-btn" @click="closeEditStudentDialog">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveStudent">
            <div class="form-group">
              <label>用户名</label>
              <input
                :value="editingStudent?.username || ''"
                type="text"
                disabled
                class="form-input"
                style="background-color: #f5f5f5;"
              />
              <small style="color: #7f8c8d; display: block; margin-top: 5px;">用户名不可修改</small>
            </div>
            <div class="form-group">
              <label>昵称 <span class="required">*</span></label>
              <input
                v-model="studentForm.nickname"
                type="text"
                placeholder="请输入昵称"
                required
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>邮箱</label>
              <input
                v-model="studentForm.email"
                type="email"
                placeholder="请输入邮箱（可选）"
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>电话</label>
              <input
                v-model="studentForm.phone"
                type="tel"
                placeholder="请输入电话（可选）"
                class="form-input"
              />
            </div>
            <div class="modal-footer">
              <button type="button" class="btn-cancel" @click="closeEditStudentDialog">取消</button>
              <button type="submit" class="btn-submit">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { childEnglishApi } from '@/api/childEnglishApi';

export default {
  name: 'StudentManagement',
  data() {
    return {
      activeTab: 'class',
      classes: [],
      students: [],
      searchKeyword: '',
      selectedClass: '',
      showAddClassDialog: false,
      editingClass: null,
      classForm: {
        name: '',
        classCategory: '',
        gradeLevel: '',
        ageRange: '',
        maxStudents: 30,
        description: ''
      },
      loading: false,
      loadingStudents: false,
      showStudentDetailDialog: false,
      studentDetail: null,
      loadingStudentDetail: false,
      showEditStudentDialog: false,
      editingStudent: null,
      studentForm: {
        nickname: '',
        email: '',
        phone: ''
      }
    };
  },
  computed: {
    filteredStudents() {
      let result = this.students;
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        result = result.filter(s => 
          s.username.toLowerCase().includes(keyword) ||
          (s.nickname && s.nickname.toLowerCase().includes(keyword))
        );
      }
      if (this.selectedClass) {
        // 根据班级ID过滤
        result = result.filter(s => s.classId && s.classId.toString() === this.selectedClass.toString());
      }
      
      // 按班级分组，然后每个班级内的学生按学习进度降序排序
      const groupedByClass = {};
      result.forEach(student => {
        const classKey = student.className || '未分班';
        if (!groupedByClass[classKey]) {
          groupedByClass[classKey] = [];
        }
        groupedByClass[classKey].push(student);
      });
      
      // 对每个班级内的学生按学习进度降序排序
      Object.keys(groupedByClass).forEach(classKey => {
        groupedByClass[classKey].sort((a, b) => {
          const progressA = a.progress || 0;
          const progressB = b.progress || 0;
          return progressB - progressA; // 降序排序
        });
      });
      
      // 展平结果，保持班级顺序
      const sortedResult = [];
      Object.keys(groupedByClass).forEach(classKey => {
        sortedResult.push(...groupedByClass[classKey]);
      });
      
      return sortedResult;
    },
    groupedClasses() {
      const groups = {};
      
      // 按班级类别分组
      this.classes.forEach(classItem => {
        // 使用 classCategory 字段，如果没有则使用 '其他班级'
        const category = classItem.classCategory || '其他班级';
        
        if (!groups[category]) {
          groups[category] = [];
        }
        groups[category].push(classItem);
      });
      
      // 按预定义顺序排序分组
      const orderedGroups = {};
      const order = ['提高', '进阶', '基础', '启蒙', '其他班级'];
      order.forEach(cat => {
        if (groups[cat]) {
          orderedGroups[cat] = groups[cat];
        }
      });
      
      return orderedGroups;
    }
  },
  mounted() {
    this.loadClasses();
    // 只在学生信息管理标签页时才加载学生数据
    if (this.activeTab === 'info') {
      this.loadStudents();
    }
  },
  watch: {
    activeTab(newTab) {
      // 当切换到学生信息管理标签页时，加载学生数据
      if (newTab === 'info') {
        this.loadStudents();
      }
    },
    selectedClass() {
      // 只在学生信息管理标签页时，才根据班级筛选重新加载
      if (this.activeTab === 'info') {
        this.loadStudents();
      }
    }
  },
  methods: {
    async loadClasses() {
      this.loading = true;
      try {
        const response = await childEnglishApi.getClasses();
        if (response && response.code === 200 && response.data && response.data.classes) {
          this.classes = response.data.classes;
        } else {
          console.error('获取班级列表失败:', response);
          // 使用 alert 作为后备方案，如果项目中有 message 组件会自动使用
          if (this.$message) {
            this.$message.error('获取班级列表失败，请稍后重试');
          } else {
            alert('获取班级列表失败，请稍后重试');
          }
        }
      } catch (error) {
        console.error('获取班级列表异常:', error);
        // 使用 alert 作为后备方案
        if (this.$message) {
          this.$message.error('获取班级列表失败: ' + (error.message || '网络错误'));
        } else {
          alert('获取班级列表失败: ' + (error.message || '网络错误'));
        }
      } finally {
        this.loading = false;
      }
    },
    async loadStudents() {
      // 只在学生信息管理标签页时才加载
      if (this.activeTab !== 'info') {
        return;
      }
      
      this.loadingStudents = true;
      try {
        const classId = this.selectedClass || null;
        console.log('开始加载学生数据, classId:', classId);
        const response = await childEnglishApi.getStudents(classId);
        
        console.log('学生数据API响应:', response);
        console.log('响应类型:', typeof response);
        console.log('响应code:', response?.code);
        console.log('响应data:', response?.data);
        
        // 检查响应格式
        if (!response) {
          console.error('响应为空');
          this.students = [];
          return;
        }
        
        // 只要响应成功（code=200），就设置学生列表（可能为空）
        if (response.code === 200) {
          console.log('API调用成功，code=200');
          
          // 检查data字段
          if (response.data) {
            console.log('响应有data字段:', response.data);
            
            // 检查students字段
            if (response.data.students !== undefined) {
              const studentsList = Array.isArray(response.data.students) ? response.data.students : [];
              console.log('获取到学生数据:', studentsList.length, '条');
              console.log('学生数据内容:', studentsList);
              this.students = studentsList;
              console.log('学生列表已更新:', this.students.length, '条');
            } else {
              console.warn('响应data中没有students字段，data内容:', response.data);
              this.students = [];
            }
          } else {
            console.warn('响应中没有data字段');
            this.students = [];
          }
        } else {
          // 如果响应不成功，记录错误但不显示弹窗（避免干扰用户）
          console.error('获取学生列表失败，code不是200:', response.code, 'message:', response.message);
          this.students = [];
        }
      } catch (error) {
        console.error('获取学生列表异常:', error);
        console.error('错误详情:', error.response?.data || error.message);
        // 出错时设置为空数组，不显示错误弹窗
        this.students = [];
      } finally {
        this.loadingStudents = false;
      }
    },
    goBack() {
      this.$router.push('/');
    },
    viewClassStudents(classItem) {
      this.activeTab = 'info';
      this.selectedClass = classItem.id;
      // 切换标签页后会自动触发 watch，但为了确保数据加载，这里也调用一次
      this.$nextTick(() => {
        this.loadStudents();
      });
    },
    editClass(classItem) {
      this.editingClass = classItem;
      this.classForm = {
        name: classItem.name || '',
        classCategory: classItem.classCategory || '',
        gradeLevel: classItem.gradeLevel || '',
        ageRange: classItem.ageRange || '',
        maxStudents: classItem.maxStudents || 30,
        description: classItem.description || ''
      };
      this.showAddClassDialog = true;
    },
    closeClassDialog() {
      this.showAddClassDialog = false;
      this.editingClass = null;
      this.classForm = {
        name: '',
        classCategory: '',
        gradeLevel: '',
        ageRange: '',
        maxStudents: 30,
        description: ''
      };
    },
    async saveClass() {
      try {
        const classData = {
          name: this.classForm.name,
          classCategory: this.classForm.classCategory,
          gradeLevel: this.classForm.gradeLevel,
          ageRange: this.classForm.ageRange,
          maxStudents: this.classForm.maxStudents,
          description: this.classForm.description
        };

        let response;
        if (this.editingClass) {
          // 更新班级
          response = await childEnglishApi.updateClass(this.editingClass.id, classData);
        } else {
          // 创建班级
          response = await childEnglishApi.createClass(classData);
        }

        if (response && response.code === 200) {
          // 保存是否为编辑模式（在关闭对话框前）
          const isEditing = !!this.editingClass;
          
          if (isEditing) {
            // 更新班级：立即更新本地数组中的对应项
            const index = this.classes.findIndex(c => c.id === this.editingClass.id);
            if (index !== -1) {
              this.classes[index] = {
                ...this.classes[index],
                name: classData.name,
                classCategory: classData.classCategory,
                gradeLevel: classData.gradeLevel,
                ageRange: classData.ageRange,
                maxStudents: classData.maxStudents,
                description: classData.description
              };
            }
          } else {
            // 创建班级：立即添加到本地数组（乐观更新）
            // 从响应中获取班级ID（可能是 classId 或 class_id）
            const classId = response.data?.classId || response.data?.class_id || Date.now();
            const newClass = {
              id: classId,
              name: classData.name,
              classCategory: classData.classCategory,
              gradeLevel: classData.gradeLevel,
              ageRange: classData.ageRange,
              maxStudents: classData.maxStudents,
              studentCount: 0,
              description: classData.description
            };
            this.classes.push(newClass);
          }
          
          // 等待 Vue 完成响应式更新
          await this.$nextTick();
          // 等待浏览器完成重绘（双重 requestAnimationFrame 确保在下一帧显示）
          await new Promise(resolve => {
            requestAnimationFrame(() => {
              requestAnimationFrame(() => {
                // 再等待一小段时间确保 DOM 完全更新
                setTimeout(resolve, 50);
              });
            });
          });
          
          // 关闭对话框
          this.closeClassDialog();
          
          // 显示成功消息（此时班级已经出现在列表中了）
          if (this.$message) {
            this.$message.success(isEditing ? '修改班级成功' : '创建班级成功');
          } else {
            alert(isEditing ? '修改班级成功' : '创建班级成功');
          }
          
          // 在后台重新加载班级列表确保数据同步（不阻塞UI）
          this.loadClasses();
        } else {
          const errorMsg = response?.message || '操作失败';
          if (this.$message) {
            this.$message.error(errorMsg);
          } else {
            alert(errorMsg);
          }
        }
      } catch (error) {
        console.error('保存班级失败:', error);
        const errorMsg = error.response?.data?.message || error.message || '操作失败';
        if (this.$message) {
          this.$message.error('保存班级失败: ' + errorMsg);
        } else {
          alert('保存班级失败: ' + errorMsg);
        }
      }
    },
    async deleteClass(classItem) {
      // 检查班级中是否有学生
      if (classItem.studentCount > 0) {
        if (this.$message) {
          this.$message.warning(`该班级中还有 ${classItem.studentCount} 名学生，无法删除。请先将学生转班后再删除。`);
        } else {
          alert(`该班级中还有 ${classItem.studentCount} 名学生，无法删除。请先将学生转班后再删除。`);
        }
        return;
      }

      // 确认删除
      const confirmed = confirm(`确定要删除班级 "${classItem.name}" 吗？\n\n删除后该班级将无法恢复。`);
      if (!confirmed) {
        return;
      }

      try {
        const response = await childEnglishApi.deleteClass(classItem.id);
        if (response && response.code === 200) {
          // 先立即从本地数组中移除该班级，实现乐观更新（UI立即更新）
          this.classes = this.classes.filter(c => c.id !== classItem.id);
          
          // 等待 Vue 完成响应式更新
          await this.$nextTick();
          // 等待浏览器完成重绘（双重 requestAnimationFrame 确保在下一帧显示）
          await new Promise(resolve => {
            requestAnimationFrame(() => {
              requestAnimationFrame(() => {
                // 再等待一小段时间确保 DOM 完全更新
                setTimeout(resolve, 50);
              });
            });
          });
          
          // 显示成功消息（此时班级已经从列表中消失了）
          if (this.$message) {
            this.$message.success('删除班级成功');
          } else {
            alert('删除班级成功');
          }
          
          // 在后台重新加载班级列表确保数据同步（不阻塞UI）
          this.loadClasses();
        } else {
          const errorMsg = response?.message || '删除失败';
          if (this.$message) {
            this.$message.error(errorMsg);
          } else {
            alert(errorMsg);
          }
        }
      } catch (error) {
        console.error('删除班级失败:', error);
        const errorMsg = error.response?.data?.message || error.message || '删除失败';
        if (this.$message) {
          this.$message.error('删除班级失败: ' + errorMsg);
        } else {
          alert('删除班级失败: ' + errorMsg);
        }
        // 如果删除失败，重新加载列表以确保数据正确
        await this.loadClasses();
      }
    },
    async viewStudentDetail(student) {
      this.showStudentDetailDialog = true;
      this.loadingStudentDetail = true;
      this.studentDetail = null;
      
      try {
        const studentId = student.id || student.userId;
        if (!studentId) {
          if (this.$message) {
            this.$message.error('学生ID不存在');
          } else {
            alert('学生ID不存在');
          }
          this.closeStudentDetailDialog();
          return;
        }
        
        const response = await childEnglishApi.getStudentDetail(studentId);
        if (response && response.code === 200 && response.data) {
          this.studentDetail = response.data;
        } else {
          const errorMsg = response?.message || '获取学生详情失败';
          if (this.$message) {
            this.$message.error(errorMsg);
          } else {
            alert(errorMsg);
          }
        }
      } catch (error) {
        console.error('获取学生详情失败:', error);
        const errorMsg = error.response?.data?.message || error.message || '获取学生详情失败';
        if (this.$message) {
          this.$message.error('获取学生详情失败: ' + errorMsg);
        } else {
          alert('获取学生详情失败: ' + errorMsg);
        }
      } finally {
        this.loadingStudentDetail = false;
      }
    },
    closeStudentDetailDialog() {
      this.showStudentDetailDialog = false;
      this.studentDetail = null;
      this.loadingStudentDetail = false;
    },
    async editStudent(student) {
      this.editingStudent = student;
      this.studentForm = {
        nickname: student.nickname || '',
        email: student.email || '',
        phone: student.phone || ''
      };
      this.showEditStudentDialog = true;
    },
    closeEditStudentDialog() {
      this.showEditStudentDialog = false;
      this.editingStudent = null;
      this.studentForm = {
        nickname: '',
        email: '',
        phone: ''
      };
    },
    async saveStudent() {
      if (!this.editingStudent) {
        return;
      }
      
      try {
        const studentId = this.editingStudent.id || this.editingStudent.userId;
        if (!studentId) {
          if (this.$message) {
            this.$message.error('学生ID不存在');
          } else {
            alert('学生ID不存在');
          }
          return;
        }
        
        const studentData = {
          nickname: this.studentForm.nickname,
          email: this.studentForm.email || null,
          phone: this.studentForm.phone || null
        };
        
        const response = await childEnglishApi.updateStudent(studentId, studentData);
        if (response && response.code === 200) {
          // 立即更新本地数组中的学生信息（乐观更新）
          const index = this.students.findIndex(s => (s.id || s.userId) === studentId);
          if (index !== -1) {
            this.students[index] = {
              ...this.students[index],
              nickname: studentData.nickname,
              email: studentData.email,
              phone: studentData.phone
            };
          }
          
          // 等待 Vue 完成响应式更新
          await this.$nextTick();
          // 等待浏览器完成重绘
          await new Promise(resolve => {
            requestAnimationFrame(() => {
              requestAnimationFrame(() => {
                setTimeout(resolve, 50);
              });
            });
          });
          
          // 关闭对话框
          this.closeEditStudentDialog();
          
          // 显示成功消息
          if (this.$message) {
            this.$message.success('修改学生信息成功');
          } else {
            alert('修改学生信息成功');
          }
          
          // 在后台重新加载学生列表确保数据同步
          this.loadStudents();
        } else {
          const errorMsg = response?.message || '操作失败';
          if (this.$message) {
            this.$message.error(errorMsg);
          } else {
            alert(errorMsg);
          }
        }
      } catch (error) {
        console.error('保存学生信息失败:', error);
        const errorMsg = error.response?.data?.message || error.message || '操作失败';
        if (this.$message) {
          this.$message.error('保存学生信息失败: ' + errorMsg);
        } else {
          alert('保存学生信息失败: ' + errorMsg);
        }
      }
    }
  }
};
</script>

<style scoped>
.student-management {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.back-btn {
  padding: 10px 20px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
}

.back-btn:hover {
  background: #2980b9;
  transform: translateX(-3px);
}

.page-header h1 {
  margin: 0;
  color: #2c3e50;
  font-size: 2em;
}

.tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  background: white;
  padding: 10px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.tab-btn {
  flex: 1;
  padding: 15px 20px;
  background: #f8f9fa;
  border: 2px solid transparent;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  color: #5d6d7e;
  transition: all 0.3s;
}

.tab-btn:hover {
  background: #e9ecef;
}

.tab-btn.active {
  background: #667eea;
  color: white;
  border-color: #667eea;
}

.tab-content {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  min-height: 500px;
}

@media (max-width: 768px) {
  .tab-content {
    padding: 20px;
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 15px;
}

@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .section-header h2 {
    margin-bottom: 10px;
  }
  
  .section-header .btn-primary {
    width: 100%;
  }
}

.section-header h2 {
  margin: 0;
  color: #2c3e50;
}

.search-bar {
  display: flex;
  gap: 10px;
}

.search-input {
  padding: 10px 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  min-width: 250px;
}

.class-filter {
  padding: 10px 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
}

.btn-primary {
  padding: 12px 24px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: all 0.3s;
}

.btn-primary:hover {
  background: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.4);
}

.class-list-container {
  padding: 10px 0;
}

.class-category {
  margin-bottom: 40px;
}

.class-category:last-child {
  margin-bottom: 0;
}

.category-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 3px solid #667eea;
}

.category-title {
  margin: 0;
  color: #2c3e50;
  font-size: 22px;
  font-weight: 700;
}

.category-count {
  color: #7f8c8d;
  font-size: 14px;
  font-weight: 500;
}

.class-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
}

@media (max-width: 768px) {
  .class-list {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}

@media (min-width: 1200px) {
  .class-list {
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  }
}

.class-card {
  border: 1px solid #e0e0e0;
  border-radius: 16px;
  padding: 24px;
  background: #ffffff;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 180px;
}

.class-card:hover {
  border-color: #667eea;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.15);
  transform: translateY(-4px);
}

.class-header {
  margin-bottom: 20px;
  flex: 1;
}

.class-header h3 {
  margin: 0 0 12px 0;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
  line-height: 1.4;
}

.class-info {
  color: #7f8c8d;
  font-size: 14px;
  line-height: 1.6;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.class-info span {
  display: inline-block;
  padding: 4px 8px;
  background: #f8f9fa;
  border-radius: 4px;
}

.class-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: auto;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.btn-secondary {
  padding: 10px 18px;
  background: #95a5a6;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
  flex: 1;
  min-width: 80px;
}

.btn-secondary:hover {
  background: #7f8c8d;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(149, 165, 166, 0.3);
}

.btn-danger {
  padding: 10px 18px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
  flex: 1;
  min-width: 80px;
}

.btn-danger:hover {
  background: #c0392b;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(231, 76, 60, 0.3);
}

.student-table {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

thead {
  background: #f8f9fa;
}

th, td {
  padding: 15px;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

th {
  font-weight: bold;
  color: #2c3e50;
}

.progress-bar {
  position: relative;
  width: 100px;
  height: 20px;
  background: #ecf0f1;
  border-radius: 10px;
  overflow: hidden;
}

.progress-fill {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background: linear-gradient(90deg, #3498db, #2ecc71);
  transition: width 0.3s;
}

.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 12px;
  font-weight: bold;
  color: #2c3e50;
  z-index: 1;
}

.btn-link {
  background: none;
  border: none;
  color: #3498db;
  cursor: pointer;
  padding: 5px 10px;
  margin: 0 5px;
  text-decoration: underline;
}

.btn-link:hover {
  color: #2980b9;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #7f8c8d;
  grid-column: 1 / -1;
}

.empty-state p {
  font-size: 18px;
  margin: 0;
}

.empty-state.loading {
  color: #667eea;
  font-weight: 500;
}

/* 对话框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e0e0e0;
}

.modal-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 20px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 28px;
  color: #7f8c8d;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s;
}

.close-btn:hover {
  background: #f0f0f0;
  color: #2c3e50;
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #2c3e50;
  font-weight: 500;
  font-size: 14px;
}

.required {
  color: #e74c3c;
}

.form-input {
  width: 100%;
  padding: 12px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #3498db;
}

.form-input[type="number"] {
  -moz-appearance: textfield;
}

.form-input[type="number"]::-webkit-inner-spin-button,
.form-input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

textarea.form-input {
  resize: vertical;
  min-height: 80px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #e0e0e0;
}

.btn-cancel {
  padding: 10px 20px;
  background: #95a5a6;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
}

.btn-cancel:hover {
  background: #7f8c8d;
}

.btn-submit {
  padding: 10px 20px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
}

.btn-submit:hover {
  background: #2980b9;
}

/* 学生详情对话框样式 */
.student-detail-modal {
  max-width: 800px;
  max-height: 90vh;
}

.student-detail-content {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 30px;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.section-title {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
  padding-bottom: 10px;
  border-bottom: 2px solid #667eea;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

@media (max-width: 768px) {
  .detail-grid {
    grid-template-columns: 1fr;
  }
}

.detail-item {
  display: flex;
  align-items: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
}

.detail-item label {
  font-weight: 500;
  color: #5d6d7e;
  min-width: 80px;
  margin-right: 10px;
}

.detail-item span {
  color: #2c3e50;
  flex: 1;
}

.parents-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.parent-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 15px;
  background: #ffffff;
  transition: all 0.3s;
}

.parent-card:hover {
  border-color: #667eea;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
}

.parent-info {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

@media (max-width: 768px) {
  .parent-info {
    grid-template-columns: 1fr;
  }
}

.parent-item {
  display: flex;
  align-items: center;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
}

.parent-item label {
  font-weight: 500;
  color: #5d6d7e;
  min-width: 60px;
  margin-right: 8px;
  font-size: 14px;
}

.parent-item span {
  color: #2c3e50;
  flex: 1;
  font-size: 14px;
}

.loading-state,
.error-state,
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #7f8c8d;
}

.loading-state {
  color: #667eea;
  font-weight: 500;
}
</style>

